//
//  JCWConstantDefine.swift
//  HengYouCai
//
//  Created by wll on 2017/11/2.
//  Copyright © 2017年 lwj. All rights reserved.
//

import Foundation

///判断当前手机是否是iPhone X系列
let isiPhoneXSeries:Bool = { ()->Bool in
    var iPhoneXSeries = false;
    if UIDevice.current.userInterfaceIdiom != .phone {
        return iPhoneXSeries
    }
    if #available(iOS 11.0 , *){
        let mainWindow = UIApplication.shared.keyWindow;
        if Double((mainWindow?.safeAreaInsets.bottom)!) > 0.0{
            iPhoneXSeries = true
        }
    }
    return iPhoneXSeries
}()

///屏幕底部安全域高度
let SafeAreaInsets_Bottom:CGFloat = { () -> CGFloat in
    if #available(iOS 11.0,*) {
        return UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0;
    } else  {
        return 0.0;
    }
}()

///当前屏幕导航栏高度
let NavigationBarHeight:CGFloat = {()->CGFloat in
    if isiPhoneXSeries{
        return 88.0
    }else{
        return 64.0
    }
}()



///刷新开始页 默认1
let JCWLimitNumberStarPage: Int = 1

///刷新数量 默认10
let JCWLimitNumberPageSize: Int = 10

///登录注册输入框高度
let JCWLogRegTFH: CGFloat = 55

///登录注册输入框margin
let JCWLogRegTFMargin: CGFloat = 25



///APPID
let JCWAPPID = "1288850062"
///广告页地址key
let kJCWADGuideImageUrl = "kJCWADGuideImageUrl"

///屏幕宽
let JCWSCREENW = UIScreen.main.bounds.size.width

///屏幕高
let JCWSCREENH = UIScreen.main.bounds.size.height

let JCWShareApplication = UIApplication.shared

///拨打电话
@discardableResult func JCWCallTel(_ phoneNumber: String) -> Bool{
    if let url = URL(string: "tel:\(phoneNumber)"){
        return JCWShareApplication.openURL(url)
    }else{
        return false
    }
}

///字体大小
func Font_WL(_ f:CGFloat) -> UIFont {
    return UIFont.systemFont(ofSize: f)
}
///字体大小
func Font_Auto(_ f:CGFloat) -> UIFont {
    if JCWSCREENW < 375 {
        return UIFont.systemFont(ofSize: f*320/375)

    }
    return UIFont.systemFont(ofSize: f)
}
func BoldFont_WL(_ bf:CGFloat) -> UIFont {
    return UIFont.boldSystemFont(ofSize: bf)
}

///rgb颜色转换（16进制->10进制）
func ColorFromRGBHex_WL(_ rgbValue: Int) -> (UIColor) {
    return UIColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0,green: ((CGFloat)((rgbValue & 0xFF00) >> 8)) / 255.0,blue: ((CGFloat)(rgbValue & 0xFF)) / 255.0,alpha: 1.0);
}

///复制到粘贴板
func JCWPasteboard(_ str: String?)  {
    UIPasteboard.general.string = str
}

// /是否登录
func isLogin()->Bool{
    return (WLFileManager.readUserData(forKey: kUserSessionId) != nil)
}
///登录界面
//var LOGINVC = UIStoryboard(name: "Log", bundle: nil).instantiateInitialViewController()

///登录界面
func LOGINVC()->UIViewController{
    return kJcwGetLogInVC()
}
///倒计时 传入时间  开始回调 进行回调 完成回调
func wl_timeCountDown(_ timeCount: Int, _ begainHandler: (()->Void)?, _ repeatHandler: ((_ timeCount: Int)->Void)?, _ completionHandler: (()->Void)?) {
    
    var timeCount = timeCount
    // 在global线程里创建一个时间源
    let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    // 设定这个时间源是每秒循环一次，立即开始
    codeTimer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
    // 设定时间源的触发事件
    begainHandler?()
    codeTimer.setEventHandler(handler: {
        // 每秒计时一次
        timeCount -= 1
        // 返回主线程处理一些事件，更新UI等等
        DispatchQueue.main.async {
            repeatHandler?(timeCount)
        }
        // 时间到了取消时间源
        if timeCount <= 0 {
            codeTimer.cancel()
            DispatchQueue.main.async {
                completionHandler?()
                return
            }
        }
    })
    // 启动时间源
    codeTimer.resume()
}

/// 处理富文本
func handlerRichText(_ strs: Array<String>, _ colors: Array<UIColor>, _ fonts:Array<UIFont>) -> NSMutableAttributedString {
//    let paragraphStyle = NSMutableParagraphStyle()
//    paragraphStyle.lineSpacing = 6
    
    
    let temp = NSMutableAttributedString()
    for i in 0 ..< strs.count {
        temp.append(NSAttributedString(string: strs[i], attributes: [NSForegroundColorAttributeName: colors[i],NSFontAttributeName:fonts[i]]))
    }
//    temp.addAttributes([NSParagraphStyleAttributeName:paragraphStyle], range: NSRange(location: 0, length: temp.length))
    return temp
//    let temp = NSMutableAttributedString(string: str1, attributes: [NSForegroundColorAttributeName: color1,NSFontAttributeName:font1])
//    temp.append(NSAttributedString(string: str2, attributes: [NSForegroundColorAttributeName: color2,NSFontAttributeName:font2]))
//    temp.append(NSAttributedString(string: str3, attributes: [NSForegroundColorAttributeName: color3,NSFontAttributeName:font3]))
    
    // 行间距
    //        NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
    //        para.lineSpacing = 6;
    
}
func jumpToNextVCWithAction(action:String, currentVC:UIViewController){
    switch action {
    case "ToShare":
        currentVC.pushVC(JCWInviteFirendVC())
    case "ToLogin":
        currentVC.present(LOGINVC(), animated: true, completion: nil)
    case "ToList": //理财产品列表页面
        currentVC.tabBarController?.selectedIndex = 1
    case "ToRecharge":
         currentVC.pushVC(UIStoryboard(name: "Profile", bundle: nil).instantiateViewController(withIdentifier: "RechargeViewControllerID"))
    case "ToAccount":
        currentVC.tabBarController?.selectedIndex = 2
    case "ToRealName":
        currentVC.pushVC(InvestPrepareVC())
    case "ToRiskAssessment ":
        // 风险测评 未登录 跳登录 已经测评 跳测评结果页
        let userLevel =  WLFileManager.readUserData(forKey: kUserLevel) as! Int //[[WLFileManager readUserDataForKey:kUserLevel] integerValue];
        let accountStatus = WLFileManager.readUserData(forKey: kUserSessionId) as! String
        
        if (accountStatus.count<1) {
            currentVC.present(LOGINVC(), animated: true, completion: nil)
            return;
        }
        if (userLevel == 0) {//未设置跳转答题界面

            currentVC.pushVC(RiskAppraiseViewC())
            
        }else{///直接跳转展示结果页
            let vc = JCWRiskAssessmentResultVC()
            vc.typeIndex = userLevel
            currentVC.pushVC(vc)
        }
    default:
        debugPrint("暂无匹配")
    }
}

/// 打开网页
///
func openWebUrl(wapStatus:Bool,wapLink:String) {
    if !wapStatus {
        if let webVC = BannerWebViewVC(urlStr: wapLink + "?mixApp", title: "") {
            let web = UIWebView()
            var userAgent: String = web.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? ""
            if userAgent.contains("ios/zy") {
                debugPrint("userAgent00>>>\(userAgent)")
                userAgent.removeSubrange(userAgent.range(of: "ios/zy")!)
                debugPrint("userAgent11>>>\(userAgent)")
                UserDefaults.standard.register(defaults: ["UserAgent":userAgent])
                UserDefaults.standard.synchronize()
                
            }
            //            self.window?.topMostWindowController?.present(webVC, animated: true, completion: {
            //                self.removeFromSuperview()
            //            })
            MainTabBarViewController.obtainTopViewController()?.present(webVC, animated: true
                , completion: {
                    
            })
        }
       
    }
}

